package com.hospital.insurancedip.async;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hospital.common.core.exception.ExceptionPrint;
import com.hospital.common.core.module.entity.BaseRequest;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DataBaseValue;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.insurancedip.config.DbContextHolder;
import com.hospital.insurancedip.module.controller.vo.AddSendTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * timetask
 *
 * @description 处理微信支付功能
 * @author:louislau
 * @create 2019-11-08 08:31:47
 **/
@Service
@Slf4j
public class WxPayFunc {

    private final RestTemplate restTemplate;

    public WxPayFunc(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    private AddTaskFunc addTaskFunc;
    @Async
    public void wxPay(String params, String url, String printLog) {
        String resStr = null;
        try {

//            // 请求体
//            HashMap<String, String> hashMap = new HashMap<>();
//            hashMap.put("key", params);
//            String body = JSONObject.toJSONString(hashMap);
//
//            // 请求头
//            HttpHeaders headers = new HttpHeaders();
//            headers.add("Content-Type", "application/json; charset=utf-8");
//            headers.add("X-Api-Sign-Version", "2.0.0");
//            // 请求
//            HttpEntity<String> request = new HttpEntity<>(body, headers);

            // 使用RestTemplate请求
            JSONObject jsonObject = JSON.parseObject(params);
            jsonObject.put("hospitalCode", DataBaseValue.getDataBaseVaule(DbContextHolder.getDbType()));
            ResponseEntity<JSONObject> responseBody = restTemplate.postForEntity(url, jsonObject.toJSONString(), JSONObject.class);
            JSONObject httpBody = responseBody.getBody();
            resStr = httpBody.toJSONString();
            if ("000000".equals(httpBody.getString("respCode"))) {
                log.info(printLog + "\r\n推送描述：推送人保执行成功\r\n返回JSON:" + resStr);
            } else {
                log.info(printLog + "\r\n推送描述：推送人保执行失败\r\n返回JSON:" + resStr);
            }
        } catch (Exception e) {
            log.error(printLog + "\r\n推送描述：推送人保执行失败\r\n返回JSON:" + resStr + "\r\n异常信息：" + e.toString());
        }
    }

    @Async
    public void platformPush(String params, String url,String infno) {
        String resStr = null;
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        try {
            JSONObject jsonObject = JSON.parseObject(params);
            ResponseEntity<JSONObject> responseBody = restTemplate.postForEntity(url, jsonObject.toJSONString(), JSONObject.class);
            JSONObject httpBody = responseBody.getBody();
            resStr = httpBody.toJSONString();
        } catch (Exception e) {
            resStr = e.getMessage();
        }finally {
            stopwatch2.stop();
            String endTime = DateUtil.getAllTime();
            ExceptionPrint.printCommErrorString("同步西安平台医保嵌入式接口数据：" + infno,
                    params,
                   ""
                    , ""+ "--返回内容：" + resStr, startTime,endTime,String.valueOf(stopwatch2.getTotalTimeSeconds()));
        }
    }

    public Map<String, String> enc(BaseRequest params, String url) {
        Map<String, String> map = new HashMap<>();
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, params, String.class);
            String result = response.getBody();
            JSONObject convertValue = JSON.parseObject(result);
            if ("200".equals(convertValue.getString("code"))) {
                Object object = convertValue.get("data");
                Object parse = JSON.parse(object.toString());
                map.put("enc", JSON.toJSONString(parse));
                map.put("responseDescription", "推送描述:加密执行成功");
            } else {
                map.put("responseDescription", "推送描述:加密执行失败" + convertValue.toJSONString());
            }
        } catch (Exception e) {
            map.put("responseDescription", "推送描述:加密执行失败" + "\r\n异常信息：" + e.toString());
        } finally {
            return map;
        }
    }
    @Async
    public Tip sendRefundBillMsg(String refundBillVo, String url, RestTemplate restTemplate, String name) {
        //计费接口调用
        Tip tip = new SuccessTip(null);
        String resultStr = "";
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        try {
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(url,refundBillVo, JSONObject.class);
            //将网络连接异常的放入时间轮任务执行 start
            resultStr = response.toString();
            if (response.getStatusCode()!= HttpStatus.OK){
                setSendMessageSchdule(refundBillVo,url);
            }
            //将网络连接异常的放入时间轮任务执行 stop
            JSONObject jsonObject = response.getBody();
            if (!jsonObject.getString("infcode").equals("0") ) {
                throw new RuntimeException(jsonObject.toJSONString());
            }
            tip.setData(jsonObject);
        } catch (Exception e1) {
            tip = new ErrorTip(203,e1.getMessage());
        }finally {
            stopwatch2.stop();
            String endTime = DateUtil.getAllTime();
            ExceptionPrint.printCommErrorString("推送"+ name + "'410100'入参:",
                    refundBillVo,
                    String.valueOf(tip.getCode())
                    , tip.getMessage() + "--返回内容：" + resultStr, startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
        }
        return tip;
    }
    /**
     * 给执行失败的消息加入时间轮任务执行
     *
     * @param params
     */
    public void setSendMessageSchdule(String params,String url) {
        AddSendTask addSendTask = new AddSendTask();
        addSendTask.setUrl(url);
        addSendTask.setCode("0000");
        addSendTask.setData(params);
        addSendTask.setRetries(2);
        addSendTask.setTick(1);
        addSendTask.setUnit(TimeUnit.MINUTES);
        addTaskFunc.addTask(addSendTask);
    }
}
